package com.iot.iotplus.mqtt;

import lombok.extern.log4j.Log4j2;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Log4j2
@Component
public class SendClient {
    @Autowired
    private MqttEntity mqttEntity;
    @Autowired
    private SendCallBack sendCallBack;

    /**
     * 发送客户端连接mqtt服务器
     * @param username
     * @return
     */
    public MqttClient connect(String username){
        String clientId = UUID.randomUUID().toString().replace("-", "");
        MqttClient client = null;
        try {
            client = new MqttClient(mqttEntity.getHostUrl(), clientId, new MemoryPersistence());
            MqttConnectOptions options = new MqttConnectOptions();
            options.setUserName(username);
            options.setPassword(username.toCharArray());
            client.setCallback(sendCallBack);
            IMqttToken iMqttToken = client.connectWithResult(options);
            iMqttToken.isComplete();
        } catch (MqttException e) {
            throw new RuntimeException(e);
        }
        return client;
    }

    /**
     * 关闭和mqtt服务器的连接
     * @param client
     */
    public void close(MqttClient client) {
        try {
//            client.disconnect();
            client.close();
        } catch (MqttException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 向mqtt服务器指定主题发送消息
     * @param client
     * @param qos
     * @param topic
     * @param msg
     */
    public void publish(MqttClient client,Integer qos,String topic, String msg) {
        MqttMessage message = new MqttMessage(msg.getBytes());
        message.setQos(qos);
        message.setPayload(msg.getBytes());
        try {
            MqttTopic mqttTopic = client.getTopic(topic);
            if (mqttTopic != null) {
                MqttDeliveryToken publish = mqttTopic.publish(message);
                publish.waitForCompletion();
                log.info("MQTT消息发送" + (publish.isComplete() ? "成功" : "失败"));
            }
        } catch (MqttException e) {
            throw new RuntimeException(e);
        }finally {
            close(client);
        }
    }

}
